package com.hudsonmq.spring.handler;

import com.hudson.codec.domain.RemotingCommand;
import com.hudsonmq.spring.utils.NettyUtil;
import com.hudsonmq.spring.utils.ThreadPoolHelper;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class HandlerProcesserManage implements InitializingBean {

    /**
     * 存放不同业务对应的处理器,使用线程池异步处理,与netty线程分离,提高netty线程的利用率
     */
    private static final ConcurrentHashMap<String, Process> PROCESSER_CONCURRENT_HASH_MAP = new ConcurrentHashMap<>();

    @Resource
    private List<Process> processList;


    /**
     * @param type    业务类型
     * @param context netty上下文,负责写会响应
     * @param request 请求消息
     */
    public static void execute(String type, ChannelHandlerContext context, RemotingCommand request) {
        Process process = PROCESSER_CONCURRENT_HASH_MAP.get(type);
        if (process != null) {
            ThreadPoolHelper.DEFAULT_THREAD_POOL.exec(() -> {
                RemotingCommand response = process.process(context, request);
                if (response != null) {
                    NettyUtil.write(context.channel(), response);
                }
            });
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for (Process process : processList) {
            PROCESSER_CONCURRENT_HASH_MAP.put(process.getType(), process);
        }
    }
}
